package cn.navclub.xt.server.util;

import cn.navclub.xt.server.config.ConstantsKt;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.mysqlclient.MySQLPool;
import io.vertx.sqlclient.PoolOptions;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet;
import io.vertx.sqlclient.Tuple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DBUtil {
    private static final String CHECK_SQL = "SELECT 1";
    private static final Logger LOG = LoggerFactory.getLogger(DBUtil.class);

    private static MySQLPool client;

    /**
     * Native sql query with tuple
     */
    public static Future<RowSet<Row>> rowQuery(String sql, Tuple tuple) {
        var query = client.preparedQuery(sql);
        final Future<RowSet<Row>> future;
        if (tuple != null && tuple.size() > 0) {
            future = query.execute(tuple);
        } else {
            future = query.execute();
        }
        return future;
    }

    /**
     * Native sql query without tuple
     */
    public static Future<RowSet<Row>> rowQuery(String sql) {
        return rowQuery(sql, null);
    }

    public synchronized static Future<Void> init(Vertx vertx, JsonObject config) {

        var host = config.getString(ConstantsKt.HOST);
        var user = config.getString(ConstantsKt.USER);
        var port = config.getInteger(ConstantsKt.PORT);

        var database = config.getString(ConstantsKt.DATABASE);
        var password = config.getString(ConstantsKt.PASSWORD);

        var maxSize = config.getInteger("maxSize");
        var idleTimeOut = config.getInteger("idleTimeout");

        var connectOptions = new MySQLConnectOptions()
                .setPort(port)
                .setHost(host)
                .setDatabase(database)
                .setUser(user)
                .setPassword(password);

        var poolOptions = new PoolOptions()
                .setMaxSize(maxSize)
                .setIdleTimeout(idleTimeOut);

        return (client = MySQLPool.pool(vertx, connectOptions, poolOptions))
                .preparedQuery(CHECK_SQL)
                .execute()
                .compose(it -> Future.<Void>succeededFuture())
                .onFailure(e -> LOG.error("数据库初始化失败!", e));
    }
}
